package com.naiterui.ehp.bs.im.utils;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

/**
 * 多媒体文件工具类
 * @author mudou
 * @since 2.6.4
 */
public class MediaUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(MediaUtils.class);

    /**
     * 调用执行成功code：<code>EXCUTE_SUCCESS_STATUS</code>
     */
    private static final int EXCUTE_SUCCESS_STATUS = 0;
    /**
     * 调用超时默认值：<code>EXCUTE_TIME_OUT</code>
     */
    private static final long EXCUTE_TIME_OUT = 10 * 1000;

    /**
     * 将上传的录音转为mp3格式
     * @param inFile amr原文件地址
     * @param outFile mp3生成文件地址
     */
    public static boolean amrToMp3(String inFile, String outFile) {

        LOGGER.info("inFile:{},outFile:{},convert START;", inFile, outFile);

        try {

            DefaultExecutor executor = new DefaultExecutor();

            // 创建监控时间10秒，超过60秒则中端执行
            ExecuteWatchdog watchdog = new ExecuteWatchdog(EXCUTE_TIME_OUT);
            executor.setWatchdog(watchdog);
            executor.setExitValue(EXCUTE_SUCCESS_STATUS);

            CommandLine cmdLine = CommandLine.parse("ffmpeg -i " + inFile + " " + outFile);
            int exitValue = executor.execute(cmdLine);

            LOGGER.info("inFile:{},outFile:{},exitValue:{},convert SUCCESS ; ", inFile, outFile, exitValue);
            return true;
        } catch (Throwable e) {
            LOGGER.error("inFile:{},outFile:{},convert FAIL ; ", inFile, outFile, e);
            return false;
        }
    }

    // public static void main(String[] args) {
    // amrToMp3("/test.amr", "/test.mp3");
    // }

}
